import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col} from 'antd';
const FormItem = Form.Item;
import {FORM_OPTIONS} from '../constants';
import {injectIntl, language} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import {partOrderPlanStatus} from '../Enum';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import {hasPermissions} from './utils';
import routes from './routes';
import Export from '../common/Export';
import {PERMISSIONS} from './constants';
import WrappedInputNumber from '../common/WrappedInputNumber';

const statusList = partOrderPlanStatus.toList(language);

class QueryPanel extends React.PureComponent {
    handleFilterChange = (value, name) => {
        this.props.onChange(name, value);
    }
    handleFilterPressEnter = (value, name) => {
        this.props.onChange(name, value);
        this.props.querySearch();
    }
    onSelectDealer = record => {
        this.props.onChange('dealerId', record.id);
        this.props.onDealerInfoChange({
            id: record.id,
            code: record.code,
            name: record.name
        });
    }
    onQueryReset=() => {
        this.props.onDealerInfoChange({
            id: '',
            code: '',
            name: ''
        });
        this.props.onClickReset();
    }
    render() {
        const {formatMessage} = this.props.intl;
        const dealerInfo = this.props.dealerInfo.id ? {
            id: this.props.dealerInfo.id,
            code: this.props.dealerInfo.code,
            name: this.props.dealerInfo.name
        } : null;
        return (
            <div>
                <Form className="form-standard">
                    <Row>
                        {!this.props.initDate.isDealerUser &&
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.dealerCode',
                                defaultMessage: '总代'
                            })}{...FORM_OPTIONS.item}>
                                <DealerSelectPanel
                                    value={dealerInfo}
                                    onSelect={this.onSelectDealer} />
                            </FormItem>
                        </Col>}
                        {this.props.initDate.brands.length > 1 &&
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.brandCode',
                                defaultMessage: '品牌'
                            })}{...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="brandId"
                                    value={this.props.condition.brandId}
                                    options={this.props.brands}
                                    onChange={this.handleFilterChange}/>
                            </FormItem>
                        </Col>}
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.orderPlanYear',
                                defaultMessage: '计划年份'
                            })} {...FORM_OPTIONS.item}>
                                <WrappedInputNumber
                                    name="orderPlanYear"
                                    value={this.props.condition.orderPlanYear}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.orderPlanMonth',
                                defaultMessage: '计划月份'
                            })} {...FORM_OPTIONS.item}>
                                <WrappedInputNumber
                                    name="orderPlanMonth"
                                    value={this.props.condition.orderPlanMonth}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.status',
                                defaultMessage: '状态'
                            })} {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="status"
                                    value={this.props.condition.status}
                                    options={statusList.filter(d => d.value !== -1)}
                                    onChange={this.handleFilterChange}/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <Button key="query" type="primary"
                                onClick={this.props.querySearch} loading={this.props.loading}>
                                {formatMessage({
                                    id: 'queryPanel.search',
                                    defaultMessage: '查询'
                                })}</Button>
                            <Button key="clear" onClick={this.onQueryReset}>{formatMessage({
                                id: 'queryPanel.reset',
                                defaultMessage: '重置'
                            })}</Button>
                        </Col>
                       
                        <Col span={18} className="col-align-right">
                            {hasPermissions(this.props.permission, PERMISSIONS.historySearch) &&
                            <Button key="historySearch" href={`#${routes.historyQuery.url()}`}>
                                {this.props.intl.formatMessage({
                                    id: 'queryPanel.btn.historySearch',
                                    defaultMessage: '历史查询'
                                })}
                            </Button>}
                            {hasPermissions(this.props.permission, PERMISSIONS.export) &&
                                <Export key={PERMISSIONS.export} exportRequest={this.props.onClickExport} />}
                            {hasPermissions(this.props.permission, PERMISSIONS.add) && this.props.initDate.isDealerUser &&
                            <Button key="add" type="primary" href={`#${routes.add.url()}`}>{formatMessage({
                                id: 'queryPanel.operation.add',
                                defaultMessage: '新增'
                            })}</Button> }
                        </Col>
                    </Row>
                </Form>
            </div>
        );
    }
}

QueryPanel.propTypes = {
    brands: PropTypes.array.isRequired,
    condition: PropTypes.object.isRequired,
    dealerInfo: PropTypes.object.isRequired,
    initDate: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    permission: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    onChange: PropTypes.func.isRequired,
    onClickExport: PropTypes.func.isRequired,
    onClickReset: PropTypes.func.isRequired,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    saveQueryCondition,
    querySearch,
    resetQueryPanel,
    saveQueryDealerInfo,
    exportData
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getInitDate = selectorFactory(['page', 'domainData', 'initData']);
const getDealerInfo = selectorFactory(['page', 'appState', 'dealerInfo']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    data => {
        const brands = data.toJS();
        return brands
            ? brands.map(item => ({
                value: item.id,
                text: item.code
            }))
            : [];
    }
);
const mapStateToProps = state => ({
    condition: getConditions(state),
    initDate: getInitDate(state),
    dealerInfo: getDealerInfo(state),
    permission: getPermissions(state),
    brands: getBrands(state),
    loading: state.getIn((['page', 'domainData', 'initData', 'isFetching'])),
});

const mapDispatchToProps = dispatch => ({
    onChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    onDealerInfoChange: data => dispatch(saveQueryDealerInfo(data)),
    querySearch: () => dispatch(querySearch()),
    onClickReset: () => dispatch(resetQueryPanel()),
    onClickExport: () => dispatch(exportData()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
